import React, { useState, useEffect } from 'react';
import {
  Row,
  Col,
  Card,
  Button,
  Input,
  Select,
  Space,
  Tag,
  Empty,
  message,
  Spin,
  Modal,
  Form,
  Tabs,
  Tooltip,
  Badge,
  Drawer,
  Typography,
  Divider,
  Upload,
  Progress,
  Alert
} from 'antd';
import {
  FileTextOutlined,
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  CopyOutlined,
  DownloadOutlined,
  UploadOutlined,
  StarOutlined,
  StarFilled,
  BulbOutlined,
  ExperimentOutlined,
  ThunderboltOutlined,
  BookOutlined,
  RobotOutlined,
  FileAddOutlined,
  ClockCircleOutlined,
  FireOutlined
} from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import { useTemplateStore } from '@/stores/template.store';
import { templateService } from '@/services/template.service';
import TemplateExtractor from '@/components/templates/TemplateExtractor';
import TemplateEditor from '@/components/templates/TemplateEditor';
import TemplateCard from '@/components/templates/TemplateCard';
import './style.css';

const { Title, Text, Paragraph } = Typography;
const { TabPane } = Tabs;
const { Search } = Input;
const { TextArea } = Input;

// 模板分类
const TEMPLATE_CATEGORIES = {
  news: { name: '新闻报道', icon: '📰', color: '#1890ff' },
  product: { name: '产品描述', icon: '📦', color: '#52c41a' },
  tech: { name: '技术文档', icon: '💻', color: '#722ed1' },
  email: { name: '邮件模板', icon: '📧', color: '#fa8c16' },
  social: { name: '社交媒体', icon: '📱', color: '#eb2f96' },
  blog: { name: '博客文章', icon: '✍️', color: '#13c2c2' },
  marketing: { name: '营销文案', icon: '📢', color: '#f5222d' },
  academic: { name: '学术论文', icon: '🎓', color: '#1890ff' },
  creative: { name: '创意写作', icon: '🎨', color: '#fa541c' },
  business: { name: '商务文档', icon: '💼', color: '#2f54eb' }
};

const TemplatesPage: React.FC = () => {
  const navigate = useNavigate();
  const {
    templates,
    favoriteTemplates,
    recentTemplates,
    loadTemplates,
    toggleFavorite,
    addToRecent,
    createTemplate,
    updateTemplate,
    deleteTemplate
  } = useTemplateStore();

  const [loading, setLoading] = useState(false);
  const [searchText, setSearchText] = useState('');
  const [selectedCategory, setSelectedCategory] = useState('all');
  const [showExtractor, setShowExtractor] = useState(false);
  const [showEditor, setShowEditor] = useState(false);
  const [editingTemplate, setEditingTemplate] = useState<any>(null);
  const [activeTab, setActiveTab] = useState('all');

  useEffect(() => {
    loadTemplates();
  }, []);

  // 过滤模板
  const filteredTemplates = templates.filter(template => {
    const matchesSearch = !searchText || 
      template.name.toLowerCase().includes(searchText.toLowerCase()) ||
      template.description?.toLowerCase().includes(searchText.toLowerCase());
    
    const matchesCategory = selectedCategory === 'all' || template.category === selectedCategory;
    
    return matchesSearch && matchesCategory;
  });

  // 获取不同类型的模板
  const favoriteTemplateList = templates.filter(t => favoriteTemplates.includes(t.id));
  const recentTemplateList = recentTemplates
    .map(id => templates.find(t => t.id === id))
    .filter(Boolean);

  // 处理使用模板
  const handleUseTemplate = (template: any) => {
    addToRecent(template.id);
    // 跳转到编辑器并带上模板
    navigate('/editor', { 
      state: { 
        template: template,
        fromTemplateLibrary: true 
      } 
    });
    message.success(`正在使用模板：${template.name}`);
  };

  // 处理编辑模板
  const handleEditTemplate = (template: any) => {
    setEditingTemplate(template);
    setShowEditor(true);
  };

  // 处理删除模板
  const handleDeleteTemplate = async (templateId: string) => {
    Modal.confirm({
      title: '确认删除',
      content: '删除后无法恢复，确定要删除这个模板吗？',
      onOk: async () => {
        await deleteTemplate(templateId);
        message.success('模板已删除');
      }
    });
  };

  // 处理从样例提炼模板
  const handleExtractComplete = (extractedTemplate: any) => {
    setShowExtractor(false);
    setEditingTemplate(extractedTemplate);
    setShowEditor(true);
    message.success('模板提炼完成，请继续编辑');
  };

  // 渲染模板网格
  const renderTemplateGrid = (templateList: any[]) => {
    if (templateList.length === 0) {
      return (
        <Empty 
          description="暂无模板"
          image={Empty.PRESENTED_IMAGE_SIMPLE}
        >
          <Button 
            type="primary" 
            icon={<PlusOutlined />}
            onClick={() => setShowExtractor(true)}
          >
            创建模板
          </Button>
        </Empty>
      );
    }

    return (
      <Row gutter={[16, 16]}>
        {templateList.map(template => (
          <Col key={template.id} xs={24} sm={12} md={8} lg={6}>
            <TemplateCard
              template={template}
              isFavorite={favoriteTemplates.includes(template.id)}
              onUse={() => handleUseTemplate(template)}
              onEdit={() => handleEditTemplate(template)}
              onDelete={() => handleDeleteTemplate(template.id)}
              onToggleFavorite={() => toggleFavorite(template.id)}
              onPreview={() => {
                Modal.info({
                  title: template.name,
                  width: 800,
                  content: (
                    <div>
                      <Paragraph>{template.description}</Paragraph>
                      <Divider />
                      <pre style={{ 
                        background: '#f5f5f5', 
                        padding: '16px',
                        borderRadius: '4px',
                        maxHeight: '400px',
                        overflow: 'auto'
                      }}>
                        {template.content}
                      </pre>
                    </div>
                  )
                });
              }}
            />
          </Col>
        ))}
      </Row>
    );
  };

  return (
    <div className="templates-page">
      {/* 页面头部 */}
      <div className="page-header">
        <Row align="middle" justify="space-between">
          <Col>
            <Title level={2} style={{ margin: 0 }}>
              <BookOutlined /> 模板库
            </Title>
            <Text type="secondary">选择模板快速开始创作，或从样例文章提炼新模板</Text>
          </Col>
          <Col>
            <Space>
              <Button
                type="primary"
                icon={<BulbOutlined />}
                size="large"
                onClick={() => setShowExtractor(true)}
              >
                从样例提炼模板
              </Button>
              <Button
                icon={<PlusOutlined />}
                size="large"
                onClick={() => {
                  setEditingTemplate(null);
                  setShowEditor(true);
                }}
              >
                创建模板
              </Button>
            </Space>
          </Col>
        </Row>
      </div>

      {/* 搜索和筛选栏 */}
      <Card className="filter-card" bodyStyle={{ padding: '16px' }}>
        <Row gutter={16} align="middle">
          <Col flex="auto">
            <Search
              placeholder="搜索模板名称或描述"
              allowClear
              enterButton
              size="large"
              value={searchText}
              onChange={(e) => setSearchText(e.target.value)}
              prefix={<FileTextOutlined />}
            />
          </Col>
          <Col>
            <Select
              value={selectedCategory}
              onChange={setSelectedCategory}
              style={{ width: 200 }}
              size="large"
            >
              <Select.Option value="all">全部分类</Select.Option>
              {Object.entries(TEMPLATE_CATEGORIES).map(([key, cat]) => (
                <Select.Option key={key} value={key}>
                  <Space>
                    <span>{cat.icon}</span>
                    <span>{cat.name}</span>
                  </Space>
                </Select.Option>
              ))}
            </Select>
          </Col>
        </Row>
      </Card>

      {/* 快速访问标签 */}
      <div className="quick-access">
        <Space size="large">
          <Tag 
            icon={<StarFilled />} 
            color="gold"
            style={{ cursor: 'pointer', padding: '4px 12px', fontSize: '14px' }}
            onClick={() => setActiveTab('favorites')}
          >
            收藏的模板 ({favoriteTemplateList.length})
          </Tag>
          <Tag 
            icon={<ClockCircleOutlined />} 
            color="blue"
            style={{ cursor: 'pointer', padding: '4px 12px', fontSize: '14px' }}
            onClick={() => setActiveTab('recent')}
          >
            最近使用 ({recentTemplateList.length})
          </Tag>
          <Tag 
            icon={<FireOutlined />} 
            color="red"
            style={{ cursor: 'pointer', padding: '4px 12px', fontSize: '14px' }}
            onClick={() => setActiveTab('popular')}
          >
            热门模板
          </Tag>
        </Space>
      </div>

      {/* 模板展示区 */}
      <Tabs activeKey={activeTab} onChange={setActiveTab}>
        <TabPane tab="全部模板" key="all">
          <Spin spinning={loading}>
            {renderTemplateGrid(filteredTemplates)}
          </Spin>
        </TabPane>
        
        <TabPane tab="收藏模板" key="favorites">
          {renderTemplateGrid(favoriteTemplateList)}
        </TabPane>
        
        <TabPane tab="最近使用" key="recent">
          {renderTemplateGrid(recentTemplateList)}
        </TabPane>
        
        <TabPane tab="热门模板" key="popular">
          {renderTemplateGrid(
            templates
              .sort((a, b) => (b.usageCount || 0) - (a.usageCount || 0))
              .slice(0, 12)
          )}
        </TabPane>
      </Tabs>

      {/* 从样例提炼模板的抽屉 */}
      <Drawer
        title={
          <Space>
            <BulbOutlined />
            <span>从样例文章提炼模板</span>
          </Space>
        }
        placement="right"
        width={800}
        open={showExtractor}
        onClose={() => setShowExtractor(false)}
        bodyStyle={{ padding: 0 }}
      >
        <TemplateExtractor
          onComplete={handleExtractComplete}
          onCancel={() => setShowExtractor(false)}
        />
      </Drawer>

      {/* 模板编辑器抽屉 */}
      <Drawer
        title={
          <Space>
            <EditOutlined />
            <span>{editingTemplate ? '编辑模板' : '创建模板'}</span>
          </Space>
        }
        placement="right"
        width={900}
        open={showEditor}
        onClose={() => {
          setShowEditor(false);
          setEditingTemplate(null);
        }}
        bodyStyle={{ padding: 0 }}
      >
        <TemplateEditor
          template={editingTemplate}
          onSave={async (template) => {
            if (editingTemplate) {
              await updateTemplate(editingTemplate.id, template);
              message.success('模板已更新');
            } else {
              await createTemplate(template);
              message.success('模板已创建');
            }
            setShowEditor(false);
            setEditingTemplate(null);
            loadTemplates();
          }}
          onCancel={() => {
            setShowEditor(false);
            setEditingTemplate(null);
          }}
        />
      </Drawer>
    </div>
  );
};

export default TemplatesPage;